package com.bootx.util.ai100;

import com.bootx.entity.Article;
import com.bootx.entity.ArticleTag;
import com.bootx.util.DateUtils;
import com.bootx.util.JsonUtils;
import com.bootx.util.ai100.pojo.ArticleDetail1Response;
import com.bootx.util.ai100.pojo.ArticleItem;
import com.bootx.util.ai100.pojo.ArticleListResponse;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.Strings;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class AiTop100Utils {

    private static final HttpClient client = HttpClient.newHttpClient();



    public static List<Article> getArticleList(Integer lastIndex){
        List<Article> articles = new ArrayList<>();
        String json = String.format("""
            {
                "articleType": 0,
                "limit": 20,
                "order": "desc",
                "lastIndex": %d
            }
            """, lastIndex);


        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://aitop100-api.hytch.com/api/article/page")) // 换成你的接口
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            ArticleListResponse articleListResponse = JsonUtils.toObject(response.body(), new TypeReference<ArticleListResponse>() {
            });
            articleListResponse.getData().forEach(article -> {
                Article article1 = new Article();
                article1.setTitle(article.getTitle());
                article1.setUrl("https://www.aitop100.cn/infomation/details/"+article.getId()+".html");
                article1.setSeoKeywords(article.getKeywords());
                article1.setSeoDescription(article.getSummary());
                article1.setSeoTitle(article.getTitle());
                article1.setMemo(article.getSummary());
                article1.setCover(article.getThumbnail());
                article1.setOtherId("aitop100_"+article.getId());
                article1.setPublishDate(DateUtils.formatStringToDate(article.getPublishTime(),"yyyy-MM-dd HH:mm:ss"));
                Set<ArticleTag> articleTags = new HashSet<>();
                article.getLabels().forEach(label -> {
                    ArticleTag articleTag = new ArticleTag();
                    articleTag.setName(label);
                    articleTags.add(articleTag);
                });
                article1.setArticleTags(articleTags);
                articles.add(article1);
            });
        }catch (Exception e){
            e.printStackTrace();
        }
        return articles;
    }


    public static String getArticleDetail(String url){
        System.out.println(url);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .build();
        String content = "";
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            Document parse = Jsoup.parse(response.body());
            Elements allElements = parse.body().getAllElements();
            allElements.forEach(node -> {
                node.removeAttr("style");
                if("script".equals(node.tagName())){
                    node.remove();
                } else if ("a".equals(node.tagName())) {
                    String href = node.attr("href");
                    if(href.indexOf("www.aitop100.cn")>0){
                        node.removeAttr("href");
                    }
                    if(!node.hasAttr("href")){
                        node.removeAttr("target");
                    }
                } else if ("0".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                } else if ("script".equals(node.tagName())) {

                }
            });

            Elements elementsByClass = parse.getElementsByClass("cont-box");
            for (Element element : elementsByClass) {
                Element article = element.getElementsByTag("article").first();
                if(article!=null && !article.html().isEmpty()){
                    clearTags(article);
                    content = article.html();
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return content;
    }

    private static void clearTags(Element article) {
        Elements p = article.getElementsByTag("p");
        AtomicInteger nextRemoveCount = new AtomicInteger(0);
        p.forEach(element -> {
            if(nextRemoveCount.get()>0){
                element.remove();
                nextRemoveCount.set(nextRemoveCount.get()-1);
            }else{
                nextRemoveCount.set(0);
                String text = element.text();
                if(Strings.CI.startsWithAny(text,"想了解更多AI创作软件工具请关注AI")){
                    element.remove();
                }else if( Strings.CI.startsWithAny(text,"想了解AITOP100平台其它版块的内容，请点击下方超链接查看")){
                    element.remove();
                    nextRemoveCount.set(1);
                }else if( Strings.CI.startsWithAny(text,"AITOP100平台官方交流社群二维码") || Strings.CI.startsWithAny(text,"AITOP100平台大赛社群二维码：")){
                    element.remove();
                    nextRemoveCount.set(1);
                }else if( Strings.CI.startsWithAny(text,"更多AI大赛请关注")){
                    element.remove();
                }else if( Strings.CI.startsWithAny(text,"AITOP100平台有收录、承办、推广各类型AI大赛活动业务")){
                    element.remove();
                }else if( Strings.CI.startsWithAny(text,"AI人工智能网站--AITOP100平台AI创作大赛专区")){
                    element.remove();
                }else if( Strings.CI.startsWithAny(text,"更多AI行业最新资讯新闻信息")){
                    element.remove();
                }else if( Strings.CI.startsWithAny(text,"更多大赛请关注")){
                    element.remove();
                }else if( Strings.CI.startsWithAny(text,"更多AI大赛请关注")){
                    element.remove();
                }else if( Strings.CI.startsWithAny(text,"更多AI大赛请关注")){
                    element.remove();
                }else if( Strings.CI.startsWithAny(text,"更多AI大赛请关注")){
                    element.remove();
                }
            }
        });
    }
    public static String getArticleDetail1(String url){
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .build();
        String content = null;
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            Document parse = Jsoup.parse(response.body());
            Element script = parse.getElementsByTag("script").getLast();
            String html = script.data();
            int i = html.indexOf("{");
            content = html.substring(i);
        }catch (Exception ignored){
        }
        return content;
    }

    public static void main(String[] args) {
        String articleDetail1 = getArticleDetail1("https://www.aitop100.cn/infomation/details/28551.html");
        ArticleDetail1Response articleDetail1Response = JsonUtils.toObject(articleDetail1, ArticleDetail1Response.class);
        System.out.println(articleDetail1Response);
    }

    //6751 有问题
    public static Article getArticle(String url) {
        String articleDetail1 = getArticleDetail1(url);
        if(articleDetail1==null){
            return null;
        }
        ArticleDetail1Response articleDetail1Response = JsonUtils.toObject(articleDetail1, ArticleDetail1Response.class);
        ArticleDetail1Response.HomeStoreBean.ArticleDetailListBean articleDetailList = articleDetail1Response.getHomeStore().getArticleDetailList();
        if(articleDetailList.getId()!=null){
            Article article = new Article();
            article.setUrl(url);
            article.setOtherId("ai100_"+articleDetailList.getId());
            article.setContent(articleDetailList.getContent());
            article.setTitle(articleDetailList.getTitle());
            article.setSeoKeywords(articleDetailList.getKeywords());
            article.setMemo(articleDetailList.getSummary());
            article.setCover(articleDetailList.getThumbnail());
            article.setSeoTitle(article.getTitle());
            article.setSeoDescription(article.getMemo());
            article.setSeoKeywords(article.getSeoKeywords());
            article.setAuthor(articleDetailList.getAuthorName());
            article.setPublishDate(DateUtils.formatStringToDate(articleDetailList.getPublishTime(),"yyyy-MM-dd HH:mm:ss"));
            List<ArticleTag> articleTags = new ArrayList<>();
            article.setSource(articleDetailList.getSource());
            articleDetailList.getLabels().forEach(label -> articleTags.add(new ArticleTag(label)));
            article.setArticleTags(new HashSet<>(articleTags));
            return article;
        }
        return null;
    }
}
